<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="dialogAddOrEdit.visible"
    :width="screenWidth"
    :fullscreen="mobile === 'mobile'"
    :title="dialogAddOrEdit.title"
    draggable
    close-icon="CloseBold"
    :close-delay="200"
    style="margin-top: 5vh"
    @close="closeDialog(false)"
  >
    <el-form
      ref="addOrEditFormRef"
      v-loading="loading"
      :model="formData"
      :rules="rules"
      label-width="170"
      size=""
      style="padding-right: 10px; overflow: auto"
    >
      <el-row justify="start" style="margin-top: 10px">
        <el-col v-if="currentSystem == 'SysUser'" :span="itemSpan">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="formData.projectName" readonly placeholder="请输入项目名称" />
            <el-button
              v-if="currentSystem == 'SysUser'"
              type="primary"
              plain
              style="position: absolute; right: -60px"
              @click="handleSelectProject"
              >选择</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="所属企业" prop="corpName">
            <el-select
              v-model="formData.corpName"
              :disabled="dialogAddOrEdit.id != undefined"
              placeholder="请选择"
              clearable
              @change="changeCorp"
            >
              <el-option v-for="item in corps" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="itemSpan">
          <el-form-item label="工资结算模式" prop="payType">
            <el-select
              v-model="formData.payType"
              :disabled="dialogAddOrEdit.id != undefined"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in salaryCalculationMethods"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="工资单类型" prop="wageType">
            <el-select
              v-model="formData.wageType"
              :disabled="dialogAddOrEdit.id != undefined"
              placeholder="请选择"
              clearable
            >
              <el-option v-for="item in wageTypes" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="当月计价总额" prop="totalValuation">
            <el-input v-model="formData.totalValuation" type="number" placeholder="请输入当月计价总额" />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="工资结算月份" prop="month">
            <el-date-picker
              v-model="formData.month"
              type="month"
              :disabled="dialogAddOrEdit.id != undefined"
              format="YYYYMM"
              value-format="YYYYMM"
              placeholder="选择工资结算月份"
              @change="changeMonth"
            />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="工资结算起始日期" prop="endDate">
            <el-input v-model="formData.startDate" disabled placeholder="请选择工资结算月份" />
            <!-- <el-date-picker
              v-model="formData.startDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            /> -->
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="工资结算结束日期" prop="endDate">
            <el-input v-model="formData.endDate" disabled placeholder="请选择工资结算月份" />
            <!-- <el-date-picker
              v-model="formData.endDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            /> -->
          </el-form-item>
        </el-col>
      </el-row>
      <select-project :dialog-select="dialogSelectProject" @select-send-close="projectSendClose"></select-project>
    </el-form>
    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">{{ dialogAddOrEdit.footBtn }}</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { CreatePayroll, UpdatePayroll, GetPayrollForm, ExtisWageAuth } from "@/api/wage/index";
import { PayrollEditForm } from "@/api/wage/types";
import { getDicts } from "@/store/modules/dict";
import { useScreen } from "@/store/modules/screen";
import { FormRules } from "element-plus/es/components/form/src/types";
import SelectProject from "@/views/common/SelectProject/index.vue";
import { getProjectCorpsNoJL } from "@/api/group/index";
import moment from "moment";

const currentSystem = ref(localStorage.getItem("usertypeName"));
const isLumpContractor = ref(localStorage.getItem("isLumpContractor"));

//声明变量
//工资计算方式
const salaryCalculationMethods = getDicts("salaryCalculationMethod");
const wageTypes = getDicts("wageType");
// 参建单位列表（需要从API获取）
const corps = ref();

//上传文件列表
const screenStore = useScreen();
const mobile = computed(() => screenStore.device);
const screenWidth = ref(900);
const itemSpan = ref(12);
const props = defineProps({
  dialogAddOrEdit: {
    type: Object,
    default: () => ({
      visible: false,
      title: "新增",
      footBtn: "确认新增",
      id: undefined,
    }),
  },
});

const { dialogAddOrEdit } = toRefs(props);

const emit = defineEmits(["sendClose"]);
const loading = ref(false);

const formData = reactive<PayrollEditForm>({});
const addOrEditFormRef = ref(ElForm);

const dialogSelectProject = reactive({
  visible: false,
  title: "选择项目",
  footBtn: "确认",
  id: 0,
  type: "allproject",
});
const handleSelectProject = function () {
  dialogSelectProject.visible = true;
};
const projectSendClose = function (info: any) {
  dialogSelectProject.visible = false;
  if (info) {
    formData.projectId = info.projectId;
    formData.projectName = info.projectName;
    formData.corpName = undefined;
    formData.corpId = undefined;
  }
};

//改变选择单位回调
const changeCorp = function (val: any) {
  let temp = corps.value.filter((item: { value: string }) => item.value == val);
  console.log(val);
  console.log(temp);
  if (temp.length > 0) {
    formData.corpId = temp[0].value;
    formData.corpName = temp[0].label;
    return;
  }
};

//表单验证规则
const rules = reactive<FormRules<PayrollEditForm>>({
  corpName: [{ required: true, message: "请选择企业", trigger: "blur" }],
  payType: [{ required: true, message: "请选择工资结算方式", trigger: "blur" }],
  month: [{ required: true, message: "请选择工资结算月份", trigger: "blur" }],
  wageType: [{ required: true, message: "请选择工资单类型", trigger: "blur" }],
});

function initScreen() {
  if (mobile.value === "mobile") {
    screenWidth.value = screenStore.screenWidth;
    itemSpan.value = 24;
  } else {
    screenWidth.value = 900;
    itemSpan.value = 12;
  }
}
const changeMonth = (val: any) => {
  // console.log(val);
  let startDate = moment(val).toDate();
  let endDate = moment(val).add(1, "months");
  endDate = endDate.add(-1, "days");

  let nowDate = new Date();
  // alert(nowDate.getFullYear()+"-"+nowDate.getMonth()+1);
  // alert(moment(endDate).format("YYYY-MM"))
  formData.startDate = moment(startDate).format("YYYY-MM-DD");
  formData.endDate = moment(endDate).format("YYYY-MM-DD");
  let month = nowDate.getMonth() + 1;
  if (moment(nowDate).format("YYYY-MM") === moment(endDate).format("YYYY-MM")) {
    let endD = nowDate.getFullYear() + "-" + month + "-" + (nowDate.getDate() - 1);
    formData.endDate = moment(endD).format("YYYY-MM-DD");
  }
};

const initCorps = async function () {
  let res = await getProjectCorpsNoJL();
  if (res.type === 0) {
    if (res.success) {
      corps.value = res.data;
    } else {
    }
  } else {
  }
};
if (currentSystem.value != "SysUser") {
  initCorps();
}

const initForm = async function () {
  if (dialogAddOrEdit.value.id == undefined) {
    let res = await GetPayrollForm(0);
    if (res.type === 0) {
      if (res.success) {
        formData.code = res.data.code;
        formData.wageType = wageTypes[0].value;
      } else {
      }
    } else {
    }
  }
  if (dialogAddOrEdit.value.id) {
    loading.value = true;
    let res = await GetPayrollForm(dialogAddOrEdit.value.id);
    loading.value = false;
    if (res.type === 0) {
      if (res.success) {
        Object.assign(formData, res.data);
      } else {
      }
    } else {
    }
  }
};

watch(
  () => [formData.month, formData.corpId, formData.wageType],
  () => {
    if (formData.wageType == 2 && formData.corpId && formData.month) {
      ExtisWageAuth({ corpId: formData.corpId, month: formData.month, wageType: formData.wageType }).then(
        (res: any) => {
          if (res.success) {
            if (!res.data) {
              ElMessage.warning("当前参建单位下该月份无权限发放非正常工资单");
            }
          }
        }
      );
    }
  }
);
onMounted(() => {
  initScreen();
  initForm();
});

/**
 * 关闭弹窗
 */
function closeDialog(needRefresh: boolean) {
  emit("sendClose", needRefresh);
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  addOrEditFormRef.value.resetFields();
  addOrEditFormRef.value.clearValidate();
  formData.projectId = undefined;
}

/**
 * 项目表单提交
 */
function handleSubmit() {
  addOrEditFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      if (dialogAddOrEdit.value.id || dialogAddOrEdit.value.id > 0) {
        UpdatePayroll(formData)
          .then((res) => {
            if (res.type === 0) {
              if (res.success === true) {
                ElMessage.success(res.msg);
                closeDialog(true);
              } else {
                ElMessage.warning(res.msg);
              }
            } else {
              ElMessage.warning(res.msg);
            }
          })
          .catch((e) => {
            console.log(e);
          })
          .finally(() => (loading.value = false));
      } else {
        formData.name =
          `【` +
          moment(formData.startDate).format("YYYY-MM-DD") +
          `至` +
          moment(formData.endDate).format("YYYY-MM-DD") +
          `_` +
          salaryCalculationMethods.find((item: { value: number }) => item.value == formData.payType).label +
          `计发】工资单`;
        CreatePayroll(formData)
          .then((resp) => {
            if (resp.type === 0) {
              if (resp.success === true) {
                ElMessage.success(resp.msg);
                closeDialog(true);
              } else {
                ElMessage.warning(resp.msg);
              }
            } else {
              ElMessage.warning(resp.msg);
            }
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}
</script>

<style lang="scss" scoped>
:deep(.el-form-item) {
  flex-wrap: wrap;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}
:deep(.el-cascader) {
  width: 100%;
}
:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item__label) {
  color: #696868;
  font-size: 13px;
}
:deep(.el-upload__tip) {
  display: inline-block;
  margin-left: 10px;
}
</style>
